// pages/teacherdetail/conreserve/conreserve.js
import { getTeacherDetail } from '../../../api/index'
import { getTimeSlotsByDate, submitAppointment } from '../../../api/booking';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    teacherDetail: {}, // 咨询师详情数据
    loading: true,
    // 选择状态
    selectedDate: '',
    selectedTime: '',
    selectedMethod: '',
    consultContent: '',
    // 日期列表
    dateList: [],
    // 时间段列表
    timeSlots: [],
    selectedTimeSlot: null,
    // 登录状态
    studentId: 0,
    isLoggedIn: false,
    loginCheckCompleted: false,
    canSubmit: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('预约页面接收到的参数:', options)
    const id = options.id
    if (id) {
      // 先保存teacherId，然后检查登录状态
      this.setData({
        'teacherDetail.id': id
      }, () => {
        this.checkLoginStatusSync()
      })
    } else {
      console.error("未获取到咨询师id")
      wx.showToast({
        title: '咨询师不存在',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 同步检查登录状态
  checkLoginStatusSync() {
    try {
      const studentInfo = wx.getStorageSync('studentInfo') || {}
      const userInfo = wx.getStorageSync('userInfo') || {}
      const loginInfo = wx.getStorageSync('loginInfo') || {}
      
      let studentId = Number(studentInfo.studentId) || Number(userInfo.studentId) || 
                      Number(loginInfo.studentId) || Number(studentInfo.id) || 
                      Number(userInfo.id) || Number(loginInfo.id) || 0
      
      const isLoggedIn = studentId > 0
      
      this.setData({
        studentId,
        isLoggedIn,
        loginCheckCompleted: true
      })
      
      if (isLoggedIn) {
        this.loadTeacherDetail(this.data.teacherDetail.id)
      } else {
        wx.showModal({
          title: '请先登录',
          content: '登录后才能进行预约操作',
          showCancel: false,
          confirmText: '立即登录',
          success: (res) => {
            if (res.confirm) {
              wx.redirectTo({ 
                url: `/pages/logs/logs?redirect=${encodeURIComponent('/pages/teacherdetail/conreserve/conreserve?id=' + this.data.teacherDetail.id)}`
              })
            } else {
              wx.navigateBack()
            }
          }
        })
      }
    } catch (err) {
      console.error('登录状态校验失败：', err)
      this.setData({
        studentId: 0,
        isLoggedIn: false,
        loginCheckCompleted: true
      })
      wx.showToast({ title: '登录状态校验失败', icon: 'none' })
    }
  },
  // 加载咨询师详情
  async loadTeacherDetail(id) {
    try {
      const { getTeacherDetail } = require('../../../api/index')
      const result = await getTeacherDetail(id)
      console.log("预约页面获取的咨询师详情", result)
      
      // 生成日期列表
      const dateList = this.generateDateList()
      
      this.setData({
        teacherDetail: result,
        dateList,
        currentDate: dateList[0].dateKey,
        loading: false
      })
      
      // 加载默认日期的时间段
      await this.loadTimeSlots(dateList[0].dateKey)
    } catch (error) {
      console.error("加载咨询师详情失败", error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },
 // 生成从明天开始的一周日期
 generateDateList() {
  const dateList = []
  const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  
  for (let i = 1; i <= 7; i++) {
    const d = new Date()
    d.setDate(d.getDate() + i)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const weekIndex = d.getDay()
    
    dateList.push({
      dateKey: `${year}${month}${day}`,
      week: weeks[weekIndex],
      day: day,
      month: month,
      year: year,
      formatDate: `${year}-${month}-${day}`
    })
  }
  
  return dateList
},

// 根据日期和咨询师ID获取时间段
async loadTimeSlots(dateKey) {
  try {
    const formatDate = `${dateKey.slice(0,4)}-${dateKey.slice(4,6)}-${dateKey.slice(6,8)}`
    const consultantId = this.data.teacherDetail.id
    
    console.log('获取时间段的参数:', { date: formatDate, consultantId })
    
    const result = await getTimeSlotsByDate({ 
      date: formatDate, 
      consultantId: consultantId 
    })
    
    if (result && result.length > 0) {
      const timeSlots = result.map(slot => {
        let timeRange
        if (slot.timeSlots) {
          timeRange = slot.timeSlots
        } else if (slot.startTime && slot.endTime) {
          timeRange = `${this.formatTime(slot.startTime)}—${this.formatTime(slot.endTime)}`
        } else {
          timeRange = '00:00—00:00'
        }
        
        return {
          timeRange: timeRange,
          original: timeRange,
          startTime: slot.startTime,
          endTime: slot.endTime,
          scheduleId: slot.scheduleId,
          availableCount: slot.availableCount || 0,
          maxAppointments: slot.maxAppointments || 1,
          bookedCount: slot.bookedCount || 0,
          status: slot.status || 0
        }
      }).filter(slot => slot.status === 0) // 只显示可预约的状态
      
      this.setData({ timeSlots })
      console.log('获取到的时间段:', timeSlots)
    } else {
      this.setData({ timeSlots: [] })
      console.log('该日期暂无可用时段')
    }
  } catch (err) {
    console.error('获取时间段失败：', err)
    this.setData({ timeSlots: [] })
    wx.showToast({ title: '获取时段失败', icon: 'none' })
  }
},

// 格式化时间数组为字符串
formatTime(timeArray) {
  if (!timeArray || !Array.isArray(timeArray)) return '00:00'
  const [hours, minutes] = timeArray
  return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
},

// 日期选择
async onDateSelect(e) {
  const date = e.currentTarget.dataset.date
  this.setData({ 
    selectedDate: date,
    selectedTime: '', // 清空已选时间
    selectedTimeSlot: null
  }, async () => {
    // 加载新日期的时间段
    await this.loadTimeSlots(date)
    this.checkSubmitStatus()
  })
},

// 时间选择
onTimeSelect(e) {
  const time = e.currentTarget.dataset.time
  const timeSlot = this.data.timeSlots.find(slot => slot.timeRange === time)
  
  if (!timeSlot) return
  
  this.setData({
    selectedTime: time,
    selectedTimeSlot: timeSlot
  }, () => {
    this.checkSubmitStatus()
  })
},

// 咨询方式选择
onMethodSelect(e) {
  const method = e.currentTarget.dataset.method
  this.setData({
    selectedMethod: method
  }, () => {
    this.checkSubmitStatus()
  })
},

// 咨询内容输入
onContentInput(e) {
  this.setData({
    consultContent: e.detail.value
  }, () => {
    this.checkSubmitStatus()
  })
},

// 检查提交状态
checkSubmitStatus() {
  const { 
    selectedDate, selectedTime, selectedMethod, 
    consultContent, isLoggedIn, loginCheckCompleted 
  } = this.data
  
  this.setData({
    canSubmit: loginCheckCompleted && isLoggedIn && 
              !!selectedDate && !!selectedTime && 
              !!selectedMethod && !!consultContent.trim()
  })
},

// 立即预约
async onReserve() {
  if (!this.data.canSubmit) {
    wx.showToast({
      title: '请完善所有预约信息',
      icon: 'none'
    })
    return
  }

  const { 
    selectedDate, selectedTimeSlot, selectedMethod, 
    consultContent, studentId, teacherDetail
  } = this.data
  
  const consultDate = `${selectedDate.slice(0,4)}-${selectedDate.slice(4,6)}-${selectedDate.slice(6,8)}`
  
  try {
    // 转换咨询方式为数字
    let consultType
    switch (selectedMethod) {
      case 'offline':
        consultType = 1 // 线下咨询
        break
      case 'online':
        consultType = 2 // 线上咨询
        break
      case 'network':
        consultType = 3 // 网络咨询
        break
      default:
        consultType = 1
    }

    // 转换时间段格式
    const timeSlot = this.convertTimeSlotFormat(selectedTimeSlot.original)
    
    const submitParams = {
      studentId: studentId,
      consultantId: teacherDetail.id,
      consultDate: consultDate,
      timeSlot: timeSlot,
      consultType: consultType,
      problemDesc: consultContent.trim(),
      remark: '从咨询师详情页面预约'
    }
    
    console.log('提交预约参数：', submitParams)
    
    const res = await submitAppointment(submitParams)
    
    if (res) {
      wx.showToast({
        title: '预约成功',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/myBooking/myBooking'
            })
          }, 1500)
        }
      })
    } else {
      wx.showToast({
        title: '预约失败，请重试',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('提交预约失败：', error)
    wx.showToast({
      title: '网络异常，请重试',
      icon: 'none'
    })
  }
},

// 转换时间段格式为 HH:mm-HH:mm
convertTimeSlotFormat(timeSlot) {
  let startTime, endTime
  if (timeSlot.includes('—')) {
    [startTime, endTime] = timeSlot.split('—')
  } else if (timeSlot.includes('-')) {
    [startTime, endTime] = timeSlot.split('-')
  } else {
    return timeSlot
  }
  
  startTime = startTime.trim()
  endTime = endTime.trim()
  
  // 移除秒部分，只保留 HH:mm
  startTime = startTime.split(':').slice(0, 2).join(':')
  endTime = endTime.split(':').slice(0, 2).join(':')
  
  return `${startTime}-${endTime}`
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})